package org.linlinjava.litemall.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.UserAccountBinding;
import org.linlinjava.litemall.db.service.UserAccountBindingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/account-binding")
@Validated
public class AdminUserAccountBindingController {
    private final Log logger = LogFactory.getLog(AdminUserAccountBindingController.class);

    @Autowired
    private UserAccountBindingService bindingService;

    /**
     * 查询用户账号绑定列表
     */
    @RequiresPermissions("admin:account-binding:list")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(required = false) Integer litemallUserId,
                       @RequestParam(required = false) String amspUserCode,
                       @RequestParam(required = false) Integer amspUserId,
                       @RequestParam(required = false) Integer bindingStatus,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "created_at") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {

        List<UserAccountBinding> bindingList = bindingService.querySelective(
                litemallUserId, amspUserCode, amspUserId, bindingStatus, page, limit);
        
        long total = bindingService.countSelective(litemallUserId, amspUserCode, amspUserId, bindingStatus);
        
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", bindingList);

        return ResponseUtil.ok(data);
    }

    /**
     * 查询绑定详情
     */
    @RequiresPermissions("admin:account-binding:read")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Long id) {
        UserAccountBinding binding = bindingService.findById(id);
        if (binding == null) {
            return ResponseUtil.fail(404, "绑定关系不存在");
        }
        return ResponseUtil.ok(binding);
    }

    /**
     * 创建绑定关系
     */
    @RequiresPermissions("admin:account-binding:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "新增")
    @PostMapping("/create")
    public Object create(@RequestBody UserAccountBinding binding) {
        if (binding == null || binding.getLitemallUserId() == null || 
            StringUtils.isEmpty(binding.getAmspUserCode())) {
            return ResponseUtil.badArgument();
        }

        // 检查是否已存在绑定关系
        if (bindingService.isBindingExists(binding.getLitemallUserId(), binding.getAmspUserCode())) {
            return ResponseUtil.fail(400, "该用户与AMSP账号的绑定关系已存在");
        }

        // 检查AMSP账号是否已被其他用户绑定
        if (!bindingService.canAmspAccountBindToUser(binding.getAmspUserCode(), binding.getLitemallUserId())) {
            Integer boundUserId = bindingService.getAmspAccountBoundUserId(binding.getAmspUserCode());
            return ResponseUtil.fail(409, "AMSP账号 " + binding.getAmspUserCode() + " 已被用户 " + boundUserId + " 绑定");
        }

        // 设置默认状态为未绑定
        if (binding.getBindingStatus() == null) {
            binding.setBindingStatus(UserAccountBinding.STATUS_UNBOUND);
        }

        int result = bindingService.add(binding);
        if (result > 0) {
            return ResponseUtil.ok(binding);
        } else {
            return ResponseUtil.fail(500, "创建绑定关系失败");
        }
    }

    /**
     * 更新绑定关系
     */
    @RequiresPermissions("admin:account-binding:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody UserAccountBinding binding) {
        if (binding == null || binding.getId() == null) {
            return ResponseUtil.badArgument();
        }

        // 检查绑定关系是否存在
        UserAccountBinding existingBinding = bindingService.findById(binding.getId());
        if (existingBinding == null) {
            return ResponseUtil.fail(404, "绑定关系不存在");
        }

        int result = bindingService.updateById(binding);
        if (result > 0) {
            return ResponseUtil.ok(binding);
        } else {
            return ResponseUtil.fail(500, "更新绑定关系失败");
        }
    }

    /**
     * 绑定账户（激活绑定）
     */
    @RequiresPermissions("admin:account-binding:bind")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "绑定")
    @PostMapping("/bind")
    public Object bindAccount(@RequestBody Map<String, Object> body) {
        Long id = ((Number) body.get("id")).longValue();
        Integer amspUserId = (Integer) body.get("amspUserId");

        if (id == null || amspUserId == null) {
            return ResponseUtil.badArgument();
        }

        // 检查绑定关系是否存在
        UserAccountBinding binding = bindingService.findById(id);
        if (binding == null) {
            return ResponseUtil.fail(404, "绑定关系不存在");
        }

        int result = bindingService.bindAccount(id, amspUserId);
        if (result > 0) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "账户绑定成功");
            response.put("bindingId", id);
            return ResponseUtil.ok(response);
        } else {
            return ResponseUtil.fail(500, "绑定账户失败");
        }
    }

    /**
     * 解绑账户
     */
    @RequiresPermissions("admin:account-binding:unbind")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "解绑")
    @PostMapping("/unbind")
    public Object unbindAccount(@RequestBody Map<String, Object> body) {
        Long id = ((Number) body.get("id")).longValue();

        if (id == null) {
            return ResponseUtil.badArgument();
        }

        // 检查绑定关系是否存在
        UserAccountBinding binding = bindingService.findById(id);
        if (binding == null) {
            return ResponseUtil.fail(404, "绑定关系不存在");
        }

        int result = bindingService.unbindAccount(id);
        if (result > 0) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "账户解绑成功");
            response.put("bindingId", id);
            return ResponseUtil.ok(response);
        } else {
            return ResponseUtil.fail(500, "解绑账户失败");
        }
    }

    /**
     * 删除绑定关系
     */
    @RequiresPermissions("admin:account-binding:delete")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody Map<String, Object> body) {
        Long id = ((Number) body.get("id")).longValue();

        if (id == null) {
            return ResponseUtil.badArgument();
        }

        // 检查绑定关系是否存在
        UserAccountBinding binding = bindingService.findById(id);
        if (binding == null) {
            return ResponseUtil.fail(404, "绑定关系不存在");
        }

        int result = bindingService.deleteById(id);
        if (result > 0) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "删除绑定关系成功");
            return ResponseUtil.ok(response);
        } else {
            return ResponseUtil.fail(500, "删除绑定关系失败");
        }
    }

    /**
     * 批量解绑用户的所有账户
     */
    @RequiresPermissions("admin:account-binding:batch-unbind")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "批量解绑")
    @PostMapping("/batch-unbind")
    public Object batchUnbind(@RequestBody Map<String, Object> body) {
        Integer litemallUserId = (Integer) body.get("litemallUserId");
        String amspUserCode = (String) body.get("amspUserCode");

        if (litemallUserId == null && StringUtils.isEmpty(amspUserCode)) {
            return ResponseUtil.badArgument();
        }

        int result = 0;
        String message = "";

        if (litemallUserId != null) {
            result = bindingService.batchUnbindByLitemallUserId(litemallUserId);
            message = "批量解绑LiteMall用户 " + litemallUserId + " 的所有账户成功，影响 " + result + " 条记录";
        } else {
            result = bindingService.batchUnbindByAmspUserCode(amspUserCode);
            message = "批量解绑AMSP用户 " + amspUserCode + " 的所有账户成功，影响 " + result + " 条记录";
        }

        Map<String, Object> response = new HashMap<>();
        response.put("message", message);
        response.put("affectedRows", result);
        return ResponseUtil.ok(response);
    }

    /**
     * 获取绑定统计信息
     */
    @RequiresPermissions("admin:account-binding:stats")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "统计")
    @GetMapping("/stats")
    public Object getStats() {
        long totalBindings = bindingService.countSelective(null, null, null, null);
        long boundCount = bindingService.countSelective(null, null, null, UserAccountBinding.STATUS_BOUND);
        long unboundCount = bindingService.countSelective(null, null, null, UserAccountBinding.STATUS_UNBOUND);

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalBindings", totalBindings);
        stats.put("boundCount", boundCount);
        stats.put("unboundCount", unboundCount);
        stats.put("bindingRate", totalBindings > 0 ? (double) boundCount / totalBindings * 100 : 0);

        return ResponseUtil.ok(stats);
    }

    /**
     * 根据LiteMall用户ID查询绑定信息
     */
    @RequiresPermissions("admin:account-binding:query-by-user")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "用户查询")
    @GetMapping("/by-user")
    public Object getBindingsByUser(@RequestParam @NotNull Integer litemallUserId) {
        List<UserAccountBinding> bindings = bindingService.queryByLitemallUserId(litemallUserId);
        
        Map<String, Object> result = new HashMap<>();
        result.put("litemallUserId", litemallUserId);
        result.put("bindings", bindings);
        result.put("bindingCount", bindings != null ? bindings.size() : 0);
        
        // 查找主要绑定
        UserAccountBinding primaryBinding = bindingService.getPrimaryBinding(litemallUserId);
        result.put("primaryBinding", primaryBinding);
        
        return ResponseUtil.ok(result);
    }

    /**
     * 根据AMSP用户代码查询绑定信息
     */
    @RequiresPermissions("admin:account-binding:query-by-amsp")
    @RequiresPermissionsDesc(menu = {"系统管理", "账号绑定管理"}, button = "AMSP查询")
    @GetMapping("/by-amsp")
    public Object getBindingsByAmsp(@RequestParam @NotNull String amspUserCode) {
        List<UserAccountBinding> bindings = bindingService.queryByAmspUserCode(amspUserCode);
        
        Map<String, Object> result = new HashMap<>();
        result.put("amspUserCode", amspUserCode);
        result.put("bindings", bindings);
        result.put("bindingCount", bindings != null ? bindings.size() : 0);
        
        // 查找有效绑定
        UserAccountBinding activeBinding = bindingService.findActiveBoundByAmspUserCode(amspUserCode);
        result.put("activeBinding", activeBinding);
        
        return ResponseUtil.ok(result);
    }
} 